package database

import (
	"errors"
	"strings"
	"wolongauth/config"
	"wolongauth/wolonghelp"
)

func NewUser(username string, password string, email string) (bool, error) {
	username = strings.TrimSpace(username)
	password = strings.TrimSpace(password)
	email = strings.TrimSpace(email)
	if HaveUser(username) {
		return false, errors.New("用户已存在！")
	}
	if len(username) < 6 {
		return false, errors.New("用户名过短！")
	}
	if len(password) < 6 {
		return false, errors.New("密码过短！")
	}
	if !wolonghelp.CheckEmail(email) {
		return false, errors.New("邮箱格式错误！")
	}
	UserDB.Create(&UserTableModel{Username: username, Password: password, Email: email, Level: User_Level_Common})
	return true, nil
}

func HaveUser(username string) bool {
	var users []UserTableModel
	UserDB.Where("username = ?", username).Find(&users)
	return len(users) > 0
}

func Login(username string, password string) (bool, error) {
	if config.IsAdmin(username, password) {
		return true, nil
	}
	if !HaveUser(username) {
		return false, errors.New("用户不存在！")
	}
	var users []UserTableModel
	UserDB.Where("username = ?", username).Find(&users)
	for _, i := range users {
		if i.Username == username && i.Password == password {
			return true, nil
		}
	}
	return false, errors.New("密码错误！")
}
